//
//  HomeMainVC.m
//  Doctor
//
//  Created by 阳光 on 16/10/10.
//  Copyright © 2016年 阳光. All rights reserved.
//

#import "HomeMainVC.h"

#import "FirstDocCell.h"
#import "VisitDocCell.h"

#import "TodayOrderCell.h"
#import "TodayConsultCell.h"
#import "TodayOperationCell.h"

#import "MessageListVC.h"

#import "DoctorHospitalListVC.h"
#import "AppDelegate.h"
#import "QBMainVC.h"
#import "QBNavigationController.h"

#define selectViewH  45

static NSString *todayOrderCellIdentifier=@"TodayOrderCellIdentifier";
static NSString *todayConsultCellIdentifier=@"TodayConsultCellIdentifier";
static NSString *todayOperationCellIdentifier=@"TodayOperationCellIdentifier";


#import "NTESSessionViewController.h"
#import "NTESVideoChatViewController.h"
#import "Reachability.h"
#import "NIMSessionListCell.h"
#import "UIView+NIM.h"
#import "NIMAvatarImageView.h"
#import "NIMKitUtil.h"
#import "NIMKit.h"
#import "UIView+NTES.h"
#import "NTESBundleSetting.h"
#import "NTESListHeader.h"
#import "NTESSnapchatAttachment.h"
#import "NTESJanKenPonAttachment.h"
#import "NTESChartletAttachment.h"
#import "NTESWhiteboardAttachment.h"
#import "NTESSessionUtil.h"
#import "FirstConsultModel.h"


@interface HomeMainVC ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate, NIMConversationManagerDelegate,NIMTeamManagerDelegate,NIMLoginManagerDelegate,NTESListHeaderDelegate, UIAlertViewDelegate>
{
    NSMutableArray *_firstConsultDataArray;
    BOOL _isLoadingFriends;
    NSInteger _currentPageFriend;
    
    UIImageView *noDataViewOne;
    UIImageView *noDataViewTwo;
    UIImageView *noDataViewThree;
}

@property(nonatomic,strong)UIView *downLine;

@property(nonatomic,assign)NSInteger currentIndex;

@property(nonatomic,strong)UIScrollView *mainScrollView;

// 初诊
@property(nonatomic,strong)UITableView *firstDocTableView;//今日预约;

// 就诊
@property(nonatomic,strong)UITableView *visitDocTableView;//今日咨询;

@end



@implementation HomeMainVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor=WhiteColor;
    
    self.title = NSLocalizedString(@"Homepage", nil);//@"首页";
    
    _firstConsultDataArray=[NSMutableArray array];
    _currentPageFriend=1;
    _isLoadingFriends=NO;
    
    
    [self initSelectView];
    
    [self initScrollView];
    
    [self initTableView];
    
    //无数据界面
    [self setNoDataView];
    
    //获取数据
    [self getLoad];
    
}

-(void)todayOrderImageEvent
{
    DoctorHospitalListVC *doctorHospitalListVC=[DoctorHospitalListVC new];
    [self.navigationController pushViewController:doctorHospitalListVC animated:NO];
}


//无数据界面;
- (void)setNoDataView
{
    
    noDataViewOne = [[UIImageView alloc] initWithFrame:_firstDocTableView.frame];
    noDataViewOne.hidden = YES;
    [_mainScrollView addSubview:noDataViewOne];
    
    noDataViewTwo = [[UIImageView alloc] initWithFrame:_visitDocTableView.frame];
    noDataViewTwo.hidden = YES;
    [_mainScrollView addSubview:noDataViewTwo];
    
    noDataViewThree = [[UIImageView alloc] initWithFrame:CGRectMake(APPW*2,0,APPW,APPH-selectViewH)];
    noDataViewThree.hidden = NO;//目前手术无界面;;;;
    [_mainScrollView addSubview:noDataViewThree];
    
    BOOL isCN = [[LanguageConvert alloc] hasShownIsCnOrNot];
    if (isCN == YES) {
        noDataViewOne.image = [UIImage imageNamed:@"appionment_cn"];
        noDataViewTwo.image = [UIImage imageNamed:@"message_cn"];
        noDataViewThree.image = [UIImage imageNamed:@"operation_cn"];
    } else if (isCN == NO){
        noDataViewOne.image = [UIImage imageNamed:@"appionment_en"];
        noDataViewTwo.image = [UIImage imageNamed:@"message_en"];
        noDataViewThree.image = [UIImage imageNamed:@"operation_en"];
    }
    
    
}


-(void)initScrollView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _mainScrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,selectViewH,APPW,APPH-selectViewH)];
    _mainScrollView.backgroundColor=ClearColor;
    _mainScrollView.showsHorizontalScrollIndicator=NO;
    _mainScrollView.pagingEnabled=YES;
    _mainScrollView.delegate=self;
    _mainScrollView.contentSize=CGSizeMake(APPW*3,APPH-125);
    [self.view addSubview:_mainScrollView];
    
}

-(void)getLoad{
    
    [self getFristConsultData];//.预约数据;
    
    [self getSesssionData];//.获取会话数据;
    
    // 获取今日手术
//    [self getLoad];
}

-(void)getload
{
    NSString *docId=[Util getUserDefaultObjectForKey:@"id"];
    NSString *startTag=[Util getNowTime];//@"1476028800";
    NSString *endTag=[Util getTodayEndTime];//@"1476115200";
    
    [QBRequest GetTodayDoneWithDocID:docId startTag:startTag endTag:endTag Success:^(id response) {
        
        NSMutableArray *info = response[@"info"];
        
        //NSLog(@"2001---%@",response);
        
        if (info.count != 0) {
            
            for (NSDictionary *dict in info) {
                
                FirstConsultModel *model = [FirstConsultModel mj_objectWithKeyValues:dict];
                [_firstConsultDataArray addObject:model];
            }
            
            _isLoadingFriends = NO;
            [_firstDocTableView.mj_header endRefreshing];
            [_firstDocTableView.mj_footer endRefreshing];
            
            [self.firstDocTableView reloadData];
            
            noDataViewOne.hidden = YES;
            _firstDocTableView.hidden = NO;
            
        } else{
            
            //无数据;
            noDataViewOne.hidden = NO;
            _firstDocTableView.hidden = YES;
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}

-(void)initTableView
{
    
    // _firstDocTableView   -今日预约
    _firstDocTableView=[[UITableView alloc]initWithFrame:CGRectMake(0,0,APPW,APPH-selectViewH) style:UITableViewStylePlain];
    _firstDocTableView.delegate=self;
    _firstDocTableView.dataSource=self;
    _firstDocTableView.backgroundColor=MAIN_BACK_COLOR;
    _firstDocTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_firstDocTableView registerClass:[TodayOrderCell class] forCellReuseIdentifier:todayOrderCellIdentifier];
    [_mainScrollView addSubview:_firstDocTableView];
    
    //.
    __weak __typeof(self) weakSelf=self;
    _firstDocTableView.mj_header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPageFriend = 1;
        [_firstConsultDataArray removeAllObjects];
        [weakSelf getFristConsultData];
    }];
    

    // _visitDocTableView   -今日会话
    _visitDocTableView=[[UITableView alloc]initWithFrame:CGRectMake(APPW,0,APPW,APPH-selectViewH) style:UITableViewStylePlain];
    _visitDocTableView.delegate=self;
    _visitDocTableView.dataSource=self;
   //    _visitDocTableView.hidden=YES;
    _visitDocTableView.backgroundColor=MAIN_BACK_COLOR;
    _visitDocTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_visitDocTableView registerClass:[TodayConsultCell class] forCellReuseIdentifier:todayConsultCellIdentifier];
    [_mainScrollView addSubview:_visitDocTableView];

}


-(void)initSelectView
{
    //标题
    UIView *titleView=[[UIView alloc]initWithFrame:CGRectMake(0,0,APPW,selectViewH)];
    titleView.backgroundColor=Color5C6E7C;
    [self.view addSubview:titleView];
    
    //NSArray *titleArr=@[@"今日预约",@"今日咨询",@"今日手术"];
     NSArray *titleArr = @[NSLocalizedString(@"MyVideo", nil),NSLocalizedString(@"MyConsult", nil),NSLocalizedString(@"MyOperation", nil)];
    
    for (int i=0;i<titleArr.count;i++){
        
        UIButton *titleArrBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        titleArrBtn.frame = CGRectMake(APPW/3.0*i,0,APPW/3.0,selectViewH);
        [titleArrBtn setTitle:titleArr[i] forState:UIControlStateNormal];
        [titleArrBtn setTitleColor:WhiteColor forState:0];
        titleArrBtn.titleLabel.font=Font_Number(16);
        [titleArrBtn addTarget:self action:@selector(titleArrBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        titleArrBtn.tag=10+i;
        if (i==0)
        {
            titleArrBtn.backgroundColor=Main_Color;
            titleArrBtn.selected=YES;
        }
        [titleView addSubview:titleArrBtn];
    }
    
}

-(void)titleArrBtnEvent:(UIButton *)sender
{
    NSInteger tag=sender.tag;
    _currentIndex=tag-10;
    _mainScrollView.contentOffset=CGPointMake(APPW*_currentIndex,0);
    _mainScrollView.scrollEnabled=YES;
    for (int i=10;i<13;i++)
    {
        UIButton *button=(UIButton *)[self.view viewWithTag:i];
        if (i==tag)
        {
            button.selected=YES;
            button.backgroundColor=Main_Color;
        }
        else
        {
            button.selected=NO;
            button.backgroundColor=Color5C6E7C;
        }
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _currentIndex=_mainScrollView.contentOffset.x/APPW;

    NSInteger tag=10+_currentIndex;

    for (int i=10;i<13;i++)
    {
        UIButton *btn=(UIButton *)[self.view viewWithTag:i];
        if (i == tag)
        {
            btn.selected=YES;
            btn.backgroundColor=Main_Color;
        }
        else
        {
            btn.selected=NO;
            btn.backgroundColor=Color5C6E7C;
        }
    }
}


#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==_firstDocTableView){
        
        return _firstConsultDataArray.count;
        
    }
    else if (tableView == self.visitDocTableView)
    {
        
        return self.recentSessions.count;
        
    }
    else
    {
        
        return 1;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView==_firstDocTableView){
        
        TodayOrderCell *cell=[tableView dequeueReusableCellWithIdentifier:todayOrderCellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
        if (_firstConsultDataArray.count != 0)
        {
            FirstConsultModel *model = _firstConsultDataArray[indexPath.row];
            [cell configureFirstCellWithModel:model];
        }
        
        return cell;
        
        
//<<<<<<< HEAD
//    }
//    else if (tableView == self.visitDocTableView)
//    {
//=======
    }
    else if (tableView == self.visitDocTableView){
        
//        TodayConsultCell
        //.
//>>>>>>> b9a907e0d06fc2387a90fa31919e6ffb3c84c955
        static NSString * cellId = @"cellId";
        NIMSessionListCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell)
        {
            cell=[[NIMSessionListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        NIMRecentSession *recent = self.recentSessions[indexPath.row];
        cell.nameLabel.text = [self nameForRecentSession:recent];
        [cell.avatarImageView setAvatarBySession:recent.session];
        [cell.nameLabel sizeToFit];
        cell.messageLabel.text  = [self contentForRecentSession:recent];
        [cell.messageLabel sizeToFit];
        cell.timeLabel.text = [self timestampDescriptionForRecentSession:recent];
        [cell.timeLabel sizeToFit];
        
        [cell refresh:recent];
        
        return cell;//

        
    } else {
        return nil;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==_firstDocTableView)
    {
        return 334/2;
    }
    else
    {
        return (162+20)/2;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == self.firstDocTableView){//预约
        
        [self videoSelectByIndex:indexPath];
    
    }else if (tableView == self.visitDocTableView){//咨询
        
        NIMRecentSession *recentSession = self.recentSessions[indexPath.row];
        
        [self onSelectedRecent:recentSession atIndexPath:indexPath];//...
        
    }
    
}

//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (tableView == self.visitDocTableView) {
//        return YES;
//    }else {
//        return NO;
//    }
//}
//
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    if (tableView == self.visitDocTableView) {
//        NIMRecentSession *recentSession = self.recentSessions[indexPath.row];
//        if (editingStyle == UITableViewCellEditingStyleDelete) {
//            [self onDeleteRecentAtIndexPath:recentSession atIndexPath:indexPath];
//        }
//    }
//    
//}


#pragma mark - 今日预约
- (void)getFristConsultData{
    
    NSString *docId = [Util getUserDefaultObjectForKey:@"id"];
    NSString *startTag = [Util getNowTime];//@"1476028800";
    NSString *endTag = [Util getTodayEndTime];//@"1476115200";
    
   [QBRequest GetTodayFirstConsultWithDocID:docId startTag:startTag endTag:endTag Success:^(id response) {
       
       NSMutableArray *info = response[@"info"];
       
       if (info.count != 0) {
           
           for (NSDictionary *dict in info) {
               
               FirstConsultModel *model = [FirstConsultModel mj_objectWithKeyValues:dict];
               [_firstConsultDataArray addObject:model];
           }
           
           _isLoadingFriends = NO;
           [_firstDocTableView.mj_header endRefreshing];
           [_firstDocTableView.mj_footer endRefreshing];
           
           [self.firstDocTableView reloadData];
           
           noDataViewOne.hidden = YES;
           _firstDocTableView.hidden = NO;
          
       } else{
       
           //无数据;
           noDataViewOne.hidden = NO;
           _firstDocTableView.hidden = YES;
           
       }
    
   } failure:^(NSError *error) {
       
   }];
    
}


#pragma mark - 今日咨询
- (void)dealloc{
    
    [[NIMSDK sharedSDK].conversationManager removeDelegate:self];
    
    [[NIMSDK sharedSDK].loginManager removeDelegate:self];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

-(void)hasNoSessionDataOrNot{//
    
    noDataViewTwo.hidden = _recentSessions.count;
    _visitDocTableView.hidden = !_recentSessions.count;
    
}

- (void)getSesssionData{
    
     self.autoRemoveRemoteSession = [[NTESBundleSetting sharedConfig] autoRemoveRemoteSession];
    
    
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    if (!self.recentSessions.count) {
        _recentSessions = [NSMutableArray array];
    }
    
    [self hasNoSessionDataOrNot];//.en = _recentSessions.count;//无有数据,控制显示;;;
    
    
    [[NIMSDK sharedSDK].conversationManager addDelegate:self];
    [[NIMSDK sharedSDK].loginManager addDelegate:self];
    
    
    extern NSString *const NIMKitTeamInfoHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTeamInfoHasUpdatedNotification:) name:NIMKitTeamInfoHasUpdatedNotification object:nil];
    
    extern NSString *const NIMKitTeamMembersHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onTeamMembersHasUpdatedNotification:) name:NIMKitTeamMembersHasUpdatedNotification object:nil];
    
    extern NSString *const NIMKitUserInfoHasUpdatedNotification;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserInfoHasUpdatedNotification:) name:NIMKitUserInfoHasUpdatedNotification object:nil];
    
}

- (void)reload
{
    //会话刷新;
    if (!self.recentSessions.count) {
        self.visitDocTableView.hidden = YES;
    }else{
        self.visitDocTableView.hidden = NO;
        [self.visitDocTableView reloadData];
    }
    
    [self hasNoSessionDataOrNot];//.
    
}



//上传该视频初诊状态
- (void)doctorUploadTheVideoOrderStatus:(NSString *)orderId{
    
    NSString *docId = [Util getUserDefaultObjectForKey:@"id"];
    [QBRequest DoctorSureThisOrderWithDocID:docId orderId:orderId Success:^(id response) {
        
        //NSLog(@"response :%@", response);

    } failure:^(NSError *error) {
        
    }];

}


//当前时间是否有效即可点击;
-(BOOL)isValidTimeForNowByStart:(NSString *)startTime ByEnd:(NSString *)endTime{
    
    BOOL isValidTime;
    
   // NSString *currentTime = [self getNowTime];
    NSString *currentTime = [Util getNowTime];
    
//    NSLog(@"currentTime :%@", currentTime);
//    NSLog(@"startTime :%@", startTime);
//    NSLog(@"endTime :%@", endTime);
    if (([currentTime intValue] >= [startTime intValue]) && ([currentTime intValue] < [endTime intValue])) {
        
        isValidTime = YES;
        
    } else {
        
        isValidTime = NO;
    }

    return isValidTime;
}


- (void)videoSelectByIndex:(NSIndexPath *)indexPath{
    
    FirstConsultModel *model = _firstConsultDataArray[indexPath.row];
    
    //是否可点击;
    BOOL isValid = [self isValidTimeForNowByStart:model.optimum_time ByEnd:model.end_time];
    
    
    if (isValid == YES) {//即可开始视频;
        
        //医生确认
        [self doctorUploadTheVideoOrderStatus:model.orders_id];
        
        //视频开始
        NSString *sessionId = model.uid;
        if ([self checkConditionById:sessionId]) {
            
            NTESVideoChatViewController *vc = [[NTESVideoChatViewController alloc] initWithCallee:sessionId];//self.session.sessionId+-+
            
            CATransition *transition = [CATransition animation];
            transition.duration = 0.25;
            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
            transition.type = kCATransitionPush;
            transition.subtype = kCATransitionFromTop;
            transition.delegate = self;
            
            [self.navigationController.view.layer addAnimation:transition forKey:nil];
            self.navigationController.navigationBarHidden = YES;
            [self.navigationController pushViewController:vc animated:NO];
        }

        
    } else if (isValid == NO){
        
        [self.view makeToast:@"预约还未开始!" duration:1 position:CSToastPositionCenter];
        return;
    }
    
}

- (BOOL)checkConditionById:(NSString *)sessionId{
    
    BOOL result = YES;

    if (![[Reachability reachabilityForInternetConnection] isReachable]) {
        [self.view makeToast:@"请检查网络" duration:2.0 position:CSToastPositionCenter];
        result = NO;
    }
    
    NSString *currentAccount = [[NIMSDK sharedSDK].loginManager currentAccount];
    
    if ([currentAccount isEqualToString:sessionId]) {//self.session.sessionId;
        
        [self.view makeToast:@"不能和自己通话哦" duration:2.0 position:CSToastPositionCenter];
        result = NO;
    }
    return result;
}

//.
//UIAlertDelegate
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//    
//    if (alertView.tag == 200) {
//        
//        if (buttonIndex == 0) {
//            
//
//        }
//    }
//    
//}


#pragma mark - sessionDelegate
//NIMConversationManagerDelegate
- (void)didAddRecentSession:(NIMRecentSession *)recentSession
           totalUnreadCount:(NSInteger)totalUnreadCount{
    [self.recentSessions addObject:recentSession];
    [self sort];
    [self reload];
}

- (void)didUpdateRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount{
    for (NIMRecentSession *recent in self.recentSessions) {
        if ([recentSession.session.sessionId isEqualToString:recent.session.sessionId]) {
            [self.recentSessions removeObject:recent];
            break;
        }
    }
    NSInteger insert = [self findInsertPlace:recentSession];
    [self.recentSessions insertObject:recentSession atIndex:insert];
    [self reload];
}

- (void)messagesDeletedInSession:(NIMSession *)session{
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    [self reload];
}

- (void)allMessagesDeleted{
    _recentSessions = [[NIMSDK sharedSDK].conversationManager.allRecentSessions mutableCopy];
    [self reload];
}

//NIMLoginManagerDelegate
- (void)onLogin:(NIMLoginStep)step
{
    if (step == NIMLoginStepSyncOK) {
        [self reload];
    }
}

- (void)onSelectedAvatar:(NSString *)userId
             atIndexPath:(NSIndexPath *)indexPath{};

- (void)onSelectedRecent:(NIMRecentSession *)recentSession atIndexPath:(NSIndexPath *)indexPath{
    
    //会话
    NIMSession *session = [NIMSession session:recentSession.session.sessionId type:NIMSessionTypeP2P];
    NTESSessionViewController *vc = [[NTESSessionViewController alloc] initWithSession:session];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)onDeleteRecentAtIndexPath:(NIMRecentSession *)recent atIndexPath:(NSIndexPath *)indexPath{
    
    id<NIMConversationManager> manager = [[NIMSDK sharedSDK] conversationManager];
    
    [manager deleteRecentSession:recent];
    
    //清理本地数据
    [self.recentSessions removeObjectAtIndex:indexPath.row];
    [self.visitDocTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    //如果删除本地会话后就不允许漫游当前会话，则需要进行一次删除服务器会话的操作
    if (self.autoRemoveRemoteSession)
    {
        [manager deleteRemoteSessions:@[recent.session]
                           completion:nil];
    }
    
    [self hasNoSessionDataOrNot];
}


- (NSString *)nameForRecentSession:(NIMRecentSession *)recent{
    if (recent.session.sessionType == NIMSessionTypeP2P) {
        return [NIMKitUtil showNick:recent.session.sessionId inSession:recent.session];
    }else{
        NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:recent.session.sessionId];
        return team.teamName;
    }
}

- (NSString *)contentForRecentSession:(NIMRecentSession *)recent{
    
    if (recent.lastMessage.messageType == NIMMessageTypeCustom) {
        
        NIMCustomObject *object = recent.lastMessage.messageObject;
        NSString *text = @"";
        
        if ([object.attachment isKindOfClass:[NTESSnapchatAttachment class]]) {
            text = @"[阅后即焚]";
        }
        else if ([object.attachment isKindOfClass:[NTESJanKenPonAttachment class]]) {
            text = @"[猜拳]";
        }
        else if ([object.attachment isKindOfClass:[NTESChartletAttachment class]]) {
            text = @"[贴图]";
        }
        else if ([object.attachment isKindOfClass:[NTESWhiteboardAttachment class]]) {
            text = @"[白板]";
        }else{
            text = @"[未知消息]";
        }
        
        if (recent.session.sessionType == NIMSessionTypeP2P) {
            return text;
            
        }else{
            
            NSString *nickName = [NTESSessionUtil showNick:recent.lastMessage.from inSession:recent.lastMessage.session];
            return nickName.length ? [nickName stringByAppendingFormat:@" : %@",text] : @"";
        }
    }
    else
    {
        return [self messageContent:recent.lastMessage];//.
    }
    
}

- (NSString *)timestampDescriptionForRecentSession:(NIMRecentSession *)recent{
    return [NIMKitUtil showTime:recent.lastMessage.timestamp showDetail:NO];
}


// Misc
- (NSInteger)findInsertPlace:(NIMRecentSession *)recentSession{
    __block NSUInteger matchIdx = 0;
    __block BOOL find = NO;
    [self.recentSessions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NIMRecentSession *item = obj;
        if (item.lastMessage.timestamp <= recentSession.lastMessage.timestamp) {
            *stop = YES;
            find  = YES;
            matchIdx = idx;
        }
    }];
    if (find) {
        return matchIdx;
    }else{
        return self.recentSessions.count;
    }
}

- (void)sort{
    
    [self.recentSessions sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        NIMRecentSession *item1 = obj1;
        NIMRecentSession *item2 = obj2;
        if (item1.lastMessage.timestamp < item2.lastMessage.timestamp) {
            return NSOrderedDescending;
        }
        if (item1.lastMessage.timestamp > item2.lastMessage.timestamp) {
            return NSOrderedAscending;
        }
        return NSOrderedSame;
    }];
}

- (void)onTouchAvatar:(id)sender{
    UIView *view = [sender superview];
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = view.superview;
    }
    UITableViewCell *cell  = (UITableViewCell *)view;
    NSIndexPath *indexPath = [self.visitDocTableView indexPathForCell:cell];
    NIMRecentSession *recent = self.recentSessions[indexPath.row];
    [self onSelectedAvatar:recent atIndexPath:indexPath];
}


// Private
- (NSString*)messageContent:(NIMMessage*)lastMessage{
    NSString *text = @"";
    switch (lastMessage.messageType) {
        case NIMMessageTypeText:
            text = lastMessage.text;
            break;
        case NIMMessageTypeAudio:
            text = @"[语音]";
            break;
        case NIMMessageTypeImage:
            text = @"[图片]";
            break;
        case NIMMessageTypeVideo:
            text = @"[视频]";
            break;
        case NIMMessageTypeLocation:
            text = @"[位置]";
            break;
        case NIMMessageTypeNotification:{
            return [self notificationMessageContent:lastMessage];
        }
        case NIMMessageTypeFile:
            text = @"[文件]";
            break;
        case NIMMessageTypeTip:
            text = lastMessage.text;
            break;
        default:
            text = @"[未知消息]";
    }
    if (lastMessage.session.sessionType == NIMSessionTypeP2P || lastMessage.messageType == NIMMessageTypeTip) {
        return text;
    }else{
        NSString *nickName = [NIMKitUtil showNick:lastMessage.from inSession:lastMessage.session];
        return nickName.length ? [nickName stringByAppendingFormat:@" : %@",text] : @"";
    }
}

- (NSString *)notificationMessageContent:(NIMMessage *)lastMessage{
    NIMNotificationObject *object = lastMessage.messageObject;
    if (object.notificationType == NIMNotificationTypeNetCall) {
        NIMNetCallNotificationContent *content = (NIMNetCallNotificationContent *)object.content;
        if (content.callType == NIMNetCallTypeAudio) {
            return @"[网络通话]";
        }
        return @"[视频聊天]";
    }
    if (object.notificationType == NIMNotificationTypeTeam) {
        NIMTeam *team = [[NIMSDK sharedSDK].teamManager teamById:lastMessage.session.sessionId];
        if (team.type == NIMTeamTypeNormal) {
            return @"[讨论组信息更新]";
        }else{
            return @"[群信息更新]";
        }
    }
    return @"[未知消息]";
}

// Notification
- (void)onUserInfoHasUpdatedNotification:(NSNotification *)notification{
    [self reload];
}

- (void)onTeamInfoHasUpdatedNotification:(NSNotification *)notification{
    [self reload];
}

- (void)onTeamMembersHasUpdatedNotification:(NSNotification *)notification{
    [self reload];
}











@end






